<template>
	<view class="body-view">
		<!--导航和状态栏-->
		<view class="state-navigation">
			<view class="slim_header_navigation d-flex a-center j-center" >
				<view class="left_box" @tap="goBack">
					<image src="/static/center/back-white.png" class="back"></image>
				</view>
				<view class="title">会员中心</view>
				<view class="right_box">
					<!-- <image src="/static/center/dian.png" class="dian"></image> -->
				</view>
			</view>
		</view>
		<!-- 顶部位置占位 -->
		<view style="height:calc(100rpx + var(--status-bar-height));"></view>
		<scroll-view scroll-y="true" class="scroll-y">
			<view class="top-info d-flex a-center">
				<view class="head-img psr">
                    <userhead width="100" height="100" :saveKey="userInfo.id" :isVip="userInfo.isVip" :src="userInfo.photo"/>
				</view>
				<view class="info-content">
					<view class="content-nickname" :class="{isVip:userInfo.isVip}">{{userInfo.nickName}}</view>
					<view class="content-id">ID：{{userInfo.id}}</view>
				</view>
			</view>
			<view v-if="userInfo.isVip==0" class="member-describe">开通VIP会员，尊享会员权益</view>
			<view v-if="userInfo.isVip==1" class="member-describe">您已是终身VIP，升级终身SVIP享更高权限</view>
			<view v-if="userInfo.isVip==2" class="member-describe">您已是终身SVIP</view>
			<view class="middle-menu ">
				<view class="menu-content">
					<view class="content-top d-flex a-center j-between">
						<view class="psr">
							<view class="content-top-title psr">终身VIP</view>
							<view class="content-top-background"></view>
						</view>
						<view class="content-top-describe">
							<view v-if="userInfo.isVip>0" class="top-describe-opened d-flex a-center j-center">
								<image class="describe-opened-image" src="@/static/image/vip-head.png"></image>
								<view class="describe-opened-text">已开通</view>
							</view>
							<view v-else class="content-top-describe">开通立享八项特权</view>
						</view>
					</view>
					<view class="menu-row d-flex">
						<view class="row-menu d-flex j-center">
							<view class="menu-cell">
								<image src="/static/image/member-center-1.png" class="menu-icon"></image>
								<view class="menu-title">会员名牌</view>
							</view>
						</view>
						<view class="row-menu d-flex j-center">
							<view class="menu-cell">
								<image src="/static/image/member-center-2.png" class="menu-icon"></image>
								<view class="menu-title">创建收费群</view>
							</view>
						</view>
						<view class="row-menu d-flex j-center">
							<view class="menu-cell">
								<image src="/static/image/member-center-3.png" class="menu-icon"></image>
								<view class="menu-title">昵称高亮</view>
							</view>
						</view>
						<view class="row-menu d-flex j-center">
							<view class="menu-cell">
								<image src="/static/image/member-center-4.png" class="menu-icon"></image>
								<view class="menu-title">优先人工服务</view>
							</view>
						</view>
					</view>
					
					<view style="height: 20rpx;"></view>
					
					<view class="menu-row d-flex">
						<view class="row-menu d-flex j-center">
							<view class="menu-cell">
								<image src="/static/image/member-center-5.png" class="menu-icon"></image>
								<view class="menu-title">更多群组辅助功能</view>
							</view>
						</view>
						<view class="row-menu d-flex j-center">
							<view class="menu-cell">
								<image src="/static/image/member-center-6.png" class="menu-icon"></image>
								<view class="menu-title">自定义服务内容</view>
							</view>
						</view>
						<view class="row-menu d-flex j-center">
							<view class="menu-cell">
								<image src="/static/image/member-center-7.png" class="menu-icon"></image>
								<view class="menu-title">群人数上限50</view>
							</view>
						</view>
						<view class="row-menu d-flex j-center">
							<view class="menu-cell">
								<image src="/static/image/member-center-8.png" class="menu-icon"></image>
								<view class="menu-title">群数量上限10</view>
							</view>
						</view>
					</view>
					<view style="height: 20rpx;"></view>
					<view class="menu-row d-flex">
						<view class="row-menu d-flex j-center">
							<view class="menu-cell">
								<image src="/static/image/member-center-12.png" class="menu-icon"></image>
								<view class="menu-title">允许转存方案</view>
							</view>
						</view>
						
					</view>
				</view>
				<view style="height: 30rpx;"></view>
				<view class="menu-content">
					<view class="content-top d-flex a-center j-between">
						<view class="psr">
							<view class="content-top-title psr">终身SVIP</view>
							<view class="content-top-background"></view>
						</view>
						<view class="content-top-describe">
							<view v-if="userInfo.isVip>1" class="top-describe-opened d-flex a-center j-center">
								<image class="describe-opened-image" src="@/static/image/svip-head.png"></image>
								<view class="describe-opened-text">已开通</view>
							</view>
							<view v-else class="content-top-describe">开通享更高特权</view>
						</view>
					</view>
					<view class="menu-row d-flex">
						<view class="row-menu d-flex j-center">
							<view class="menu-cell">
								<image src="/static/image/member-center-9.png" class="menu-icon"></image>
								<view class="menu-title">SVIP名牌</view>
							</view>
						</view>
						<view class="row-menu d-flex j-center">
							<view class="menu-cell">
								<image src="/static/image/member-center-10.png" class="menu-icon"></image>
								<view class="menu-title">群人数500</view>
							</view>
						</view>
						<view class="row-menu d-flex j-center">
							<view class="menu-cell">
								<image src="/static/image/member-center-11.png" class="menu-icon"></image>
								<view class="menu-title">群数量上限50</view>
							</view>
						</view>
						<view class="row-menu d-flex j-center">
							<view class="menu-cell">
								<image src="/static/image/member-center-13.png" class="menu-icon"></image>
								<view class="menu-title">转让或接受群主</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!--底部站位-->
			<view class="bottom-v"></view>
		</scroll-view>
		<view class="bottom-button d-flex j-center">
			<tm-button v-if="userInfo.isVip==0" class="button-button" style="margin: 0 auto;" :width="650" :shadow="-1"
			    :linear-color="['#FEE9CA', '#EBBA6E']" linear="left" :fontSize="32" fontColor="#1A1A1A" @tap="openVipFix"
			>
                <text>
                    <text>¥</text>
                    <text class="priceText">{{priceText}}</text>
                    <text style="font-weight: 600;">{{buttonText}}</text>
                </text>
            </tm-button>
			<tm-button v-if="userInfo.isVip==1" class="button-button" style="margin: 0 auto;"  :width="650" :shadow="-1"
			    :linear-color="['#FEE9CA', '#EBBA6E']" linear="left" :fontSize="32" fontColor="#1A1A1A" @tap="openVipToSvipFix"
			>
                 <view class="d-flex d-r" style="align-items: flex-end;">
                    <text>¥</text>
                    <text class="priceText">{{priceText}}</text>
                    <text style="font-weight: 600;">{{buttonText}}</text>
                </view>
            </tm-button>

                <tm-button v-if="userInfo.isVip==2" class="button-button" style="margin: 0 auto;"  :width="650" :shadow="-1"
			    :linear-color="['#FEE9CA', '#EBBA6E']" linear="left" :fontSize="32" fontColor="#1A1A1A"
			>   
                <view class="d-flex d-r a-center">
                    <text class="priceText">{{priceText}}</text>
                    <text style="font-weight: 600;">{{buttonText}}</text>
                </view>
            
            </tm-button>
		</view>
		<!--开通vip弹出框-->
		<uni-popup ref="vipPopup" :safe-area="false" :mask-click="true" @maskClick="vipFix=false">
			<view class="vip-popup">
				<view class="popup-title d-flex a-center j-center">
					<view class="title-text psr">
						<view class="text-title">开通瘦身群VIP</view>
						<view class="text-background"></view>
					</view>
					<image @tap="closeVipFix" class="title-icon" src="../../static/image/close.png"></image>
				</view>
				<view style="height: 51rpx;"></view>

                <view  class="vip_type d-flex d-c a-center j-center" v-for="(item,index) in paymentContent" @tap="chooseConsume(index)" :class="{'selected':item.selected}" :key="index">
                    <view v-if="item.selected" class="check_box d-flex a-center j-center">
                        <image class="check" src="/static/nvue/check.png" mode="" />
                    </view>
                    <view class="row1 d-flex a-center j-between">
                        <text class="text1">
                            {{item.title}}
                        </text>

                        <view>
                            <text class="text2">¥</text>
                            <text class="text3">{{item.showAmount}}</text>
                        </view>
                    </view>

                    <view class="row2 d-flex a-center j-between">
                        <text class="text1">{{item.desp}}</text>
                        <text class="text2">原价:{{item.oldAmount}}</text>
                    </view>
                </view>

				<!-- <view class="popup-row">
					<view class="row-cell" v-for="(item,index) in paymentContent" :key="index">
						<view class="cell-content" @tap="chooseConsume(index)">
							<view v-if="item.selected" class="content-selected d-flex a-center j-center">
								<i class="icon selected-icon icon-xuanzhong"></i>
							</view>
							<view class="content-left">
								<view class="content-date">{{item.title}}</view>
								<view class="content-price">{{item.describe}}</view>
							</view>
							<view class="content-right">
								<text class="right-icon">¥</text>
								<text class="right-number">{{item.showAmount}}</text>
							</view>
						</view>
					</view>
				</view> -->
				<view class="popup-button d-flex j-center">
					<tm-button class="button-button" :width="650" :shadow="-1"
					    :linear-color="['#FEE9CA', '#EBBA6E']" linear="left" :fontSize="32" fontColor="#1A1A1A" @tap="confirmPay"
					    :label="chooseConsumeButton"></tm-button>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="vipToSvipPopup" :safe-area="false" :mask-click="true" @maskClick="vipFix=false">
			<view class="vip-popup">
				<view class="popup-title d-flex a-center j-center">
					<view class="title-text psr">
						<view class="text-title">开通瘦身群VIP</view>
						<view class="text-background"></view>
					</view>
					<image @tap="vipToSvipPopup.close()" class="title-icon" src="../../static/image/close.png"></image>
				</view>
				<view style="height: 51rpx;"></view>

                <view  class="vip_type d-flex d-c a-center j-center"  :key="index">
                    <!-- <view class="check_box d-flex a-center j-center">
                        <image class="check" src="/static/nvue/check.png" mode="" />
                    </view> -->
                    <view class="row1 d-flex a-center j-between">
                        <text class="text1">
                            终身VIP
                        </text>

                        <view>
                            <text style="font-size:30rpx;font-weight:600;color:#A9792D;">已开通</text>
                        </view>
                    </view>

                    <view  class="row2 d-flex a-center j-between">
                        <text class="text1">8项会员专属权益，一次付费，终身享用</text>
                    </view>
                </view>
                
                <view  class="vip_type d-flex d-c a-center j-center" @tap="chooseConsume(index)" :class="{'selected':true}" :key="index">
                    <view  class="check_box d-flex a-center j-center">
                        <image class="check" src="/static/nvue/check.png" mode="" />
                    </view>
                    <view class="row1 d-flex a-center j-between">
                        <text class="text1">
                            {{vipToSvipContent.title}}
                        </text>

                        <view>
                            <text class="text2">补差 </text>
                            <text class="text2">¥</text>
                            <text class="text3">{{vipToSvipContent.showAmount}}</text>
                        </view>
                    </view>

                    <view class="row2 d-flex a-center j-between">
                        <text class="text1">{{vipToSvipContent.desp}}</text>
                        <text class="text2">原价:{{vipToSvipContent.oldAmount}}</text>
                    </view>
                </view>

				<!-- <view class="popup-row">
					<view class="row-cell" v-for="(item,index) in paymentContent" :key="index">
						<view class="cell-content" @tap="chooseConsume(index)">
							<view v-if="item.selected" class="content-selected d-flex a-center j-center">
								<i class="icon selected-icon icon-xuanzhong"></i>
							</view>
							<view class="content-left">
								<view class="content-date">{{item.title}}</view>
								<view class="content-price">{{item.describe}}</view>
							</view>
							<view class="content-right">
								<text class="right-icon">¥</text>
								<text class="right-number">{{item.showAmount}}</text>
							</view>
						</view>
					</view>
				</view> -->
				<view class="popup-button d-flex j-center">
					<tm-button class="button-button" :width="650" :shadow="-1"
					    :linear-color="['#FEE9CA', '#EBBA6E']" linear="left" :fontSize="32" fontColor="#1A1A1A" @tap="vipToSvip"
					    :label="`支付 ¥${vipToSvipContent.showAmount}`"></tm-button>
				</view>
			</view>
		</uni-popup>


        

		<!--支付弹出框-->
		<uni-popup ref="payPopup" :safe-area="false" :mask-click="true" @maskClick="payFix=false">
			<view class="pay-popup">
				<view class="popup-title d-flex psr a-center j-center">
					<view class="text-title">选择支付方式</view>
					<image @tap="closePayFix" class="title-icon" src="../../static/image/close.png"></image>
				</view>
				<view class="popup-amount">订单金额：¥{{selectedConsume?.showAmount}}</view>
				<view class="popup-row">
					<view class="row-cell" v-for="(item,index) in paymentMethod" :key="index">
						<view :class="`cell-content psr d-flex a-center ${item.selected?'selected':''}`" @tap="choosePay(index)">
							<image v-if="item.selected" class="cell-selected" src="../../static/image/payment-selected.png"></image>
							<image class="cell-icon" :src="item.icon"></image>
							<view class="cell-title">{{item.title}}</view>
						</view>
					</view>
				</view>
				<view class="popup-button d-flex j-center">
					<tm-button class="button-button" :width="650" :shadow="-1"
					    :linear-color="['#64F1C5', '#29DBA3']" linear="left" :fontSize="32" fontColor="#FFFFFF" @tap="submitPay"
					    label="确认支付"></tm-button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup lang="tsx" name="memberCenter">
import { ref,computed } from "vue";
import { onShow,onLoad } from "@dcloudio/uni-app";
import { userData as userDataStore } from "@/store/userData";
import { getUserDetail } from "@/api/api";
//import cacheimg from '@/components/cacheimg.vue'
import userhead from '@/components/userhead.vue'
import { systemConfig } from "@/store/systemConfig";
import { centToYuan } from "@/utils/format";
import { pay } from '@/hooks/pay';
import moment from 'moment'
import { systemInfo } from "@/store/systemInfo";
import { applePay } from "@/utils/iap";
import { showLoading,closeLoading } from "@/utils/utils";
import { checkOldOrder } from '@/utils/iap'

const SYSTEM_CONFIG:any = systemConfig()
//const vipIcon = ref(["../../static/image/vip-icon.png","../../static/image/svip-icon.png"])
const  goBack = () => {
	uni.navigateBack();
};
let userInfo: any = ref({});

const checked = ref(false);

const buttonText = computed(()=>{
    if(userInfo.value.isVip==0){
        return '开通终身VIP'
    }
    if(userInfo.value.isVip==1){
        return '升级终身SVIP'
    }
    if(userInfo.value.isVip==2){
        return '您已是终身SVIP'
    }
})

const priceText = computed(()=>{
    if(userInfo.value.isVip==0){
        return '58'
    }
    if(userInfo.value.isVip==1){
        return '28'
    }
    if(userInfo.value.isVip==2){
        return ''
    }
})

onShow(async() => {
	refreshData();//刷新当页数据
    checked.value = await checkOldOrder();
});
const userData: any = userDataStore();
const paymentContent:any = ref([]);//收费配置
const vipToSvipContent:any = ref({});//收费配置
const paymentMethod:any = ref([]);//支付配置


onLoad(()=>{
	let timer = setTimeout(function() {
		if(SYSTEM_CONFIG.userVip.length>0){
			loadConfig();//加载数据
			clearTimeout(timer); 
		}
		// 这里可以写你需要定时器执行的代码  
	}, 500);

	//loadConfig()
	
});
//加载配置信息
const loadConfig = () => {
	paymentContent.value = [];//清空
	paymentMethod.value = [];//清空
	console.log('SYSTEM_CONFIG.userVip')
	console.log('SYSTEM_CONFIG.userVip')
	console.log('SYSTEM_CONFIG.userVip')
	console.log(SYSTEM_CONFIG.userVip)
	//遍历加载VIP收费配置
	// SYSTEM_CONFIG.userVip.forEach((item:any)=>{
	// 	let slimValue = item?.slimValue?.split("|");
	// 	let data = {
	// 		selected:false,//选中状态
	// 		title:item.name,//标题
	// 		describe:"¥"+ centToYuan(slimValue[1]) +"/月",
	// 		showAmount:centToYuan(slimValue[2]),
	// 		amount:slimValue[2],
	// 		id:item.id,
	// 		type:1
	// 	}
	// 	paymentContent.value.push(data)
	// });
	//遍历加载SVIP收费配置
	SYSTEM_CONFIG.userVip.forEach((item:any)=>{


		let slimValue = item?.slimValue?.split("|");
        let title = '';
        let desp = '';
        console.log(Number(item.id))
        if(Number(item.slimKey)===1){
            title = '终身VIP'
            desp = '8项会员专属权益，一次付费，终身享用'
        }
        if(Number(item.slimKey)===2){
            title = '终身SVIP'
            desp ='含VIP所有功能'
        }
        if(Number(item.slimKey)===3){
            title = '终身SVIP'
            desp ='含VIP所有功能'
        }
		let data = {
			selected:false,//选中状态
			title,//标题
			describe:"¥"+ centToYuan(slimValue[1]) +"/月",
            desp,
            oldAmount:Number(centToYuan(slimValue[1])),
			showAmount:Number(centToYuan(slimValue[0])),
			amount:slimValue[0],
			id:item.id,
            productId:slimValue[2],
			type:2
		}

        if(item.slimKey==='1'||item.slimKey==='2'){
            paymentContent.value.push(data)
        }

        if(item.slimKey==='3'){
            vipToSvipContent.value = data;
        }

	});
	
	//遍历加载支付方式
	SYSTEM_CONFIG.payType.forEach((item:any)=>{
		let icon = "";
		if(item.slimKey==1)icon="../../static/image/WeChat.png"
		if(item.slimKey==2)icon="../../static/image/Alipay.png"
		let data = {
			selected:false,//选中状态
			icon:icon,
			title:item.slimValue,
			type:item.slimKey//支付类型
		}
		paymentMethod.value.push(data)
	});
}
//刷新当前用户信息
const refreshData = () => {
	getUserDetail({id:userData.id}).then((res: any) => {
		//console.log(res.data)
		//res.data.isVip=2;
        userData.setUserData(res.data);
		if(res.data.vipTime!=null&&res.data.vipTime!=""){
			res.data.vipTime=moment(res.data.vipTime, "YYYY-MM-DD HH:mm:ss").format("YYYY年MM月DD日")
		}
		if(res.data.svipTime!=null&&res.data.svipTime!=""){
			res.data.svipTime=moment(res.data.svipTime, "YYYY-MM-DD HH:mm:ss").format("YYYY年MM月DD日")
		}
		userInfo.value = res.data;
		//console.log(userInfo.value)
	});
}
const vipFix = ref(false)
const vipPopup = ref()
const vipToSvipPopup = ref()
const openVipFix = async() => {
    if(!checked.value){
        checked.value = await checkOldOrder();
        return;
    }
	vipFix.value = true;
    chooseConsume(0);
	vipPopup.value.open('bottom')
}

const openVipToSvipFix = async() => {
    if(!checked.value){
        checked.value = await checkOldOrder();
        return;
    }
	vipFix.value = true;
	vipToSvipPopup.value.open('bottom')
}
const closeVipToSvipFix = () => {
	vipToSvipPopup.value.close()
    vipFix.value = false;
}
/*
const paymentContent = ref([
	{
		selected:false,//选中状态
		title:"1个月VIP",//标题
		describe:"¥78/月",
		amount:78
	},{
		selected:false,//选中状态
		title:"3个月VIP",//标题
		describe:"¥78/月",
		amount:233
	},{
		selected:false,//选中状态
		title:"6个月VIP",//标题
		describe:"¥78/月",
		amount:418
	},{
		selected:false,//选中状态
		title:"SVIP年会员",//标题
		describe:"¥78/月",
		amount:798
	}
]);
*/
const selectedConsume:any = ref(null);//选中消费金额
const chooseConsumeButton = ref("请选择");
//选择费用
const chooseConsume = (index:number) =>{
	paymentContent.value.forEach((item:any,idx:number)=>{
		if(index==idx){
			item.selected = true
			chooseConsumeButton.value = "支付¥" + item.showAmount
			selectedConsume.value = item
		}else{
			item.selected = false
		}
	});
}

const closeVipFix = ()=>{
    vipFix.value=false;
    vipPopup.value.close();
    vipToSvipPopup.value.close();

}

const vipToSvip=async ()=>{
    selectedConsume.value = vipToSvipContent.value;
    closeVipFix();
    console.log('vipToSvip')
    console.log('vipToSvip')
    console.log('vipToSvip')



    if(uni.platform==='ios'){
        console.log(99999)
        console.log(99999)
        console.log(99999)
        uni.showLoading({
                mask: true,
				title: '开通中,请勿关闭APP'
        });

        let obj = {
            appleProductId:selectedConsume.value.productId,
            totalAmt:selectedConsume.value.amount,
            productId:selectedConsume.value.id,
        }

        const res = await applePay(obj).catch(()=>{
            closeLoading();
            uni.showToast({
                title: "开通失败",  
                icon: 'error',  
                duration: 2000  
            });
        })

        if(res){
            uni.showToast({
                title: "开通成功",  
                icon: 'success',  
                duration: 2000  
            });
            closeLoading();
            refreshData();
        }
        return;
    }
	openPayFix();

}

const confirmPay = async () => {
	if(selectedConsume.value==null){
		uni.showToast({
		    title: "请选择金额",  
		    icon: 'error',  
		    duration: 1500  
		});
		return
	}

	closeVipFix();
	
	/*
    if(uni.platform==='ios'){

        uni.showLoading({
                mask: true,
				title: '开通中,请勿关闭APP'
        });

        let obj = {
            appleProductId:selectedConsume.value.productId,
            totalAmt:selectedConsume.value.amount,
            productId:selectedConsume.value.id,
        }

        const res = await applePay(obj).catch(()=>{
            closeLoading();
            uni.showToast({
                title: "开通失败",  
                icon: 'error',  
                duration: 2000  
            });
        })

        if(res){
            uni.showToast({
                title: "开通成功",  
                icon: 'success',  
                duration: 2000  
            });
            closeLoading();
            refreshData();
        }

        return;



    }
	*/

	openPayFix();
}
const payFix = ref(false)
const payPopup = ref()
const openPayFix = () => {
	payFix.value = true;
	payPopup.value.open('bottom')
}
const closePayFix = () => {
	payPopup.value.close()
    payFix.value = false;
}

// const paymentMethod = ref([
// 	{
// 		selected:false,//选中状态
// 		icon:"../../static/image/WeChat.png",
// 		title:"微信支付",
// 		type:1//支付类型
// 	},
// 	{
// 		selected:false,//选中状态
// 		icon:"../../static/image/Alipay.png",
// 		title:"支付宝",
// 		type:2//支付类型
// 	}
// ]);

let selectedPay: any = null;//选中的支付方式
//选择支付方式
const choosePay = (index:number) =>{
	paymentMethod.value.forEach((item:any,idx:number)=>{
		if(index==idx){
			item.selected = true
			selectedPay = item
		}else{
			item.selected = false
		}
	});
}
const submitPay = () => {
	if(selectedPay==null){
		uni.showToast({
		    title: "请选择支付方式",  
		    icon: 'error',  
		    duration: 1500  
		});
		return
	}
	// if(selectedPay.type==1){
	// 	uni.showToast({
	// 	    title: "微信支付暂未开放",  
	// 	    icon: 'error',  
	// 	    duration: 1500  
	// 	});
	// 	return
	// }
	//支付宝支付
	const payParams = {
	    slimType:1,
	    totalAmt:selectedConsume?.value?.amount,
	    productId:selectedConsume?.value?.id,
	    payType:selectedPay.type,
	}

    console.log('payParams')
    console.log(payParams)


	pay(payParams).then((res:any) => {
		//console.log(res)
        refreshData();
	});
	closePayFix();
}
</script>

<style lang="scss" scoped>
@import './memberCenter.scss';
.priceText{
    margin-right:10rpx;
    font-size:42rpx;
	font-weight: 600;
}
</style>
